package com.mall.malllibrary.ui.loader

import android.content.Context
import android.view.Gravity
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AppCompatDialog
import androidx.constraintlayout.widget.ConstraintSet.Layout
import com.blankj.utilcode.util.ScreenUtils
import com.mall.malllibrary.R
import com.wang.avi.AVLoadingIndicatorView
import com.wang.avi.Indicator
import com.wang.avi.indicators.BallScaleMultipleIndicator

object MallLoader {

    private var LOADERS = ArrayList<AppCompatDialog>()

    // 默认的loader
    private val DEFAULT_LOADING = BallScaleMultipleIndicator()
    // 动态创建
    private fun createDialog(
        context:Context?,
        loadingview:AVLoadingIndicatorView
    ):AppCompatDialog{
        val dialog = AppCompatDialog(context!!, R.style.dialog)
//        获取屏幕的宽高
        val swidth = ScreenUtils.getScreenWidth()
        val sheight = ScreenUtils.getScreenHeight()
        val dialogWindow = dialog.window
        dialog.setContentView(loadingview)
        // 设置dialog相关属性
        if (dialogWindow != null){
            val lp = dialogWindow.attributes
            lp.width = swidth/8
            lp.height = sheight/8
            lp.height = lp.height+sheight/10
            lp.gravity = Gravity.CENTER
        }

        LOADERS.add(dialog)
        return dialog
    }



    fun showLoading(context: Context?, type: Enum<LoaderStyle>){
        showLoading(context, type.name)
    }

    fun showLoading(context: Context?, type: String){
        val avLoadingIndicatorView = AVLoadingIndicatorView(context)
        avLoadingIndicatorView.setIndicator(type)
        createDialog(context!!, avLoadingIndicatorView).show()
    }

    @JvmOverloads
    fun showLoading(context: Context?, indicator: Indicator= DEFAULT_LOADING){
        val avLoadingIndicatorView = AVLoadingIndicatorView(context)
        avLoadingIndicatorView.indicator = indicator
        createDialog(context!!, avLoadingIndicatorView).show()
    }

    fun stopLoading(){
        for (dialog in LOADERS){
            if (dialog.isShowing){
                dialog.cancel()
            }
        }
        LOADERS.clear()
    }

}